package com.kokotchy.tuxcontrol;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;

public class Preferences extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	private static final String TAG = "TuxControlPreferences";

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equals("port_server_preference")) {
			String port = sharedPreferences.getString("port_server_preference",
					"54321");
			SharedPreferences.Editor editor = sharedPreferences.edit();
			try {
				editor.putInt("port_server", Integer.parseInt(port));
			} catch (NumberFormatException e) {
				editor.putInt("port_server", 54321);
			}
			editor.commit();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String pattern = "onActivityResult(requestCode=%d, resultCode=%d, data=%s)";
		Log.i(TAG, String.format(pattern, requestCode, resultCode, data
				.toString()));
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.prefs);
		getPreferenceScreen().getSharedPreferences()
				.registerOnSharedPreferenceChangeListener(this);
	}

	@Override
	protected void onDestroy() {
		Log.i(TAG, "onDestroy");
		super.onDestroy();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		String pattern = "onNewIntent(intent=%s)";
		Log.i(TAG, String.format(pattern, intent.toString()));
		super.onNewIntent(intent);
	}

	@Override
	protected void onRestoreInstanceState(Bundle state) {
		String pattern = "onRestoreInstanceState(state=%s)";
		Log.i(TAG, String.format(pattern, state.toString()));
		super.onRestoreInstanceState(state);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		String pattern = "onSaveInstanceState(outState=%s)";
		Log.i(TAG, String.format(pattern, outState.toString()));
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i(TAG, "Stop preferences");
		setResult(RESULT_OK);
		finish();
	}
}
